package com.haha.qqchannelbot.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
@Log4j2
public class FreeAPIService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private ObjectMapper objectMapper;

    private final static String GPT3_5_URL = "https://api.lolimi.cn/API/AI/ys3.5.php?msg=%s&speaker=%s";
    private final static String SPEECH_GENERATION_URL = "https://api.lolimi.cn/API/yyhc/y.php?msg=%s&speaker=%s";
    private final static String HISTORY_TODAY_URL = "https://api.lolimi.cn/API/lishi/api.php?n=5";

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    FreeAPIService() {
        log.info("FreeAPIService init");
    }

    public String gpt3_5(String msg, String speaker) {
        String result = null;
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(
                    String.format(GPT3_5_URL, msg, speaker),
                    HttpMethod.GET, null, String.class);
            String body = exchange.getBody();
            System.out.println(body);
            Map<String, Object> map = objectMapper.readValue(body, Map.class);
            result = String.valueOf(map.get("msg"));
        } catch (JsonProcessingException e) {
            log.error("json解析错误", e);
        } catch (Exception e) {
            log.error("", e);
        }

        return result;
    }

    /**
     * 语音生成，指定人
     * @param msg
     * @param speaker
     * @return
     */
    public InputStream speechGeneration(String msg, String speaker, String localFilePath, String outputFilePath) {
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(
                    String.format(SPEECH_GENERATION_URL, msg, speaker),
                    HttpMethod.GET, null, String.class);
            String body = exchange.getBody();
            log.info("speechGeneration body, {}", body);
            Map<String, Object> map = objectMapper.readValue(body, Map.class);
            String result = null;
            result = String.valueOf(map.get("music"));
            if (result != null) {
                getFile(result, localFilePath);
//                WavToAmrConverter.any(localFilePath, outputFilePath);
                InputStream resourceAsStream = new FileInputStream(outputFilePath);
                return resourceAsStream;
            }
        } catch (JsonProcessingException e) {
            log.error("json解析错误", e);
        } catch (Exception e) {
            log.error("", e);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public String getFile(String fileUrl, String localFilePath) {
        ResponseEntity<byte[]> response = restTemplate.getForEntity(fileUrl, byte[].class);
        if (response.getStatusCode().is2xxSuccessful()) {
            byte[] fileBytes = response.getBody();

            try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
                fos.write(fileBytes);
            } catch (IOException e) {
                log.error("写入文件失败", e);
            }
        } else {
            log.error("Failed to retrieve the file from the remote URL.");
        }
        return localFilePath;
    }

    public String giveYouColorToSeeSee() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity("https://api.lolimi.cn/API/kout/k.php?msg=5&type=text", String.class);
        return forEntity.getBody();
    }

    public String historyToday() {
        ResponseEntity<String> forEntity = restTemplate.getForEntity(HISTORY_TODAY_URL, String.class);
        Date date = new Date();
        String format = sdf.format(date);
        String body = forEntity.getBody();
        body = "今天是" + format + "\n" + body;
        return body;
    }

    public static void main(String[] args) {
//        FreeAPIService freeAPIService = new FreeAPIService();
//        freeAPIService.speechGeneration("你好啊，我是派蒙", "派蒙", "./tmp/65323baa0240b.mp3", "./tmp/65323baa0240b.silk");
//        freeAPIService.getFile("https://api.lolimi.cn/API/yyhc/ys/65323d3fc97fa.mp3", "./tmp/65323baa0240b.mp3");
//        System.out.println(giveYouColorToSeeSee());
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(HISTORY_TODAY_URL, String.class);
        System.out.println(forEntity.getBody());
    }

}
